package com.zx.lc.config;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

/**
 * 模拟使用redis存储会话上下文
 */
@Slf4j
public class RedisChatStore implements ChatMemoryStore {

    private static Map<String, List<ChatMessage>> CACHE = new ConcurrentHashMap<>();

    @Override
    public List<ChatMessage> getMessages(Object o) {
        String key = o.toString();
        List<ChatMessage> messageList = CACHE.get(key);
        if (CollectionUtils.isEmpty(messageList)) {
            messageList = new ArrayList<>();
            CACHE.put(key, messageList);
        }
        log.info("从redis获得会话, memoryId={}, messageList={}", key, messageList);
        return messageList;
    }

    @Override
    public void updateMessages(Object o, List<ChatMessage> messageList) {
        String key = o.toString();
        log.info("更新redis会话, memoryId={}, messageList={}", key, messageList);
        CACHE.put(key, messageList);
    }

    @Override
    public void deleteMessages(Object o) {
        getMessages(o).clear();
    }
}
